package cn.iocoder.yudao.module.book.controller.app.eargrinding;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.book.controller.admin.books.vo.BooksPageReqVO;
import cn.iocoder.yudao.module.book.controller.app.bookcase.vo.AppBooksRespVO;
import cn.iocoder.yudao.module.book.controller.app.booksShell.vo.AppCollectionsRespVO;
import cn.iocoder.yudao.module.book.controller.app.eargrinding.vo.AppAudioRespVO;
import cn.iocoder.yudao.module.book.dal.dataobject.collect.CollectDO;
import cn.iocoder.yudao.module.book.service.audio.AudioService;
import cn.iocoder.yudao.module.book.service.books.BooksService;
import cn.iocoder.yudao.module.book.service.collect.CollectService;
import cn.iocoder.yudao.module.book.service.collections.CollectionsService;
import cn.iocoder.yudao.module.book.service.users.userDTOService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "APP - 音频")
@RestController
@RequestMapping("/api/user")
//测试完成
public class AppAudioController {
    @Resource
    private AudioService audioService;

    @Resource
    private CollectService collectService;

    @Resource
    private userDTOService userService;

    @Resource
    private CollectionsService collectionsService;

    @Resource
    private BooksService booksService;

//    @GetMapping("/listen/list")
//    @Operation(summary = "获取用户音频列表")
//    public CommonResult<List<AppAudioRespVO>> list(@Valid @RequestParam Integer userId, @Valid @RequestParam String sort) {
//        audioService.getByUserId(userId,sort);
//        return CommonResult.success(audioService.getByUserId(userId,sort));
//    }

    @GetMapping("/listen/play")
    @Operation(summary = "播放音频")
    public CommonResult<AppAudioRespVO> playAudio(@Valid @RequestParam("bookId") Integer bookId) {
        // 记录播放行为并返回音频信息
        return CommonResult.success(audioService.playAudio(bookId, userService.getCurrentUserId()));
    }

    @GetMapping("/listen/play-page")
    @Operation(summary = "播放指定页面的音频")
    public CommonResult<AppAudioRespVO> playPageAudio(@Valid @RequestParam("bookId") Integer bookId, 
                                                     @Valid @RequestParam("imageId") Integer imageId) {
        // 记录播放行为并返回音频信息
        return CommonResult.success(audioService.playPageAudio(bookId, imageId, userService.getCurrentUserId()));
    }

    @GetMapping("/listen/my-recording")
    @Operation(summary = "获取我最近的录音音频（按书与页可选）")
    public CommonResult<AppAudioRespVO> myRecording(@RequestParam("bookId") Integer bookId,
                                                    @RequestParam(value = "page", required = false) Integer page) {
        Long userId = userService.getCurrentUserId();
        // 精确查询该用户在该书、该页的最新录音
        cn.iocoder.yudao.module.book.dal.dataobject.audio.AudioDO audio = audioService.getLatestRecording(userId, Long.valueOf(bookId), page);
        if (audio == null) return success(null);
        AppAudioRespVO vo = new AppAudioRespVO();
        vo.setBookId(bookId);
        vo.setAudioUrl(audio.getAudioUrl());
        return success(vo);
    }

    @GetMapping("/listen/stream")
    @Operation(summary = "流式下载用户录音")
    public ResponseEntity<byte[]> streamRecording(@RequestParam("bookId") Integer bookId,
                                                  @RequestParam("page") Integer page,
                                                  @RequestParam(value = "uid", required = false) Long uid) {
        try {
            Long userId = (uid != null && uid > 0) ? uid : userService.getCurrentUserId();
            cn.iocoder.yudao.module.book.dal.dataobject.audio.AudioDO recording = 
                audioService.getLatestRecording(userId, Long.valueOf(bookId), page);
            
            if (recording == null || recording.getAudioData() == null) {
                return ResponseEntity.notFound().build();
            }
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType(
                recording.getContentType() != null ? recording.getContentType() : "audio/mp3"
            ));
            headers.setContentLength(recording.getAudioData().length);
            headers.setCacheControl("max-age=3600"); // 1小时缓存
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(recording.getAudioData());
        } catch (Exception e) {
            return ResponseEntity.status(500).build();
        }
    }

    @GetMapping("/collection/listen/collect")
    @Operation(summary = "收藏音频")
    public CommonResult<Boolean> collect(@Valid @RequestParam Integer bookId) {
        return CommonResult.success(collectService.collect(bookId,userService.getCurrentUserId()));
    }

    @GetMapping("/collection/listen/remove")
    @Operation(summary = "取消收藏音频")
    public CommonResult<Boolean> remove(@Valid @RequestParam("bookId") Integer bookId) {
        return CommonResult.success(collectService.deleteCollectByBookId(bookId,userService.getCurrentUserId()));
    }

    @GetMapping("/listen/categories")
    @Operation(summary = "获取用户音频分类")
    public CommonResult<List<AppBooksRespVO>> categories(@RequestParam("lang") String lang) {
        // 将字符串语言代码转换为数字
        Integer langCode = convertLangToCode(lang);
        List<AppCollectionsRespVO> appCollectionsRespVOs = collectionsService.selectAllByLang(langCode);
        List<AppBooksRespVO> books = new ArrayList<>();
        for(AppCollectionsRespVO appCollectionsRespVO : appCollectionsRespVOs){
            List<AppBooksRespVO> byCollectionId = booksService.getByCollectionId(appCollectionsRespVO.getCollectionId());
            books.addAll(byCollectionId);
        }
        return CommonResult.success(books);
    }

    private Integer convertLangToCode(String lang) {
        switch (lang.toLowerCase()) {
            case "en":
            case "english":
                return 1;
            case "zh":
            case "chinese":
                return 2;
            default:
                return 1; // 默认英语
        }
    }

    @GetMapping("/listen/groups")
    @Operation(summary = "获取绘本列表")
    public CommonResult<List<AppBooksRespVO>> groups(@RequestParam("id") Integer id) {
        return CommonResult.success(booksService.getByCollectionId(id));
    }

    @GetMapping("/listen/recent")
    @Operation(summary = "获取最近听的音频")
    public CommonResult<List<AppAudioRespVO>> recent() {
        return CommonResult.success(audioService.getRecentAudio(userService.getCurrentUserId()));
    }

    /**
     * 我录音过的书本分页（只返回用户有录音的书）
     */
    @GetMapping("/recording/books")
    @Operation(summary = "获取我录音过的书本ID列表")
    public CommonResult<List<Long>> myRecordedBooks() {
        return success(audioService.listMyRecordedBookIds(userService.getCurrentUserId()));
    }

    @GetMapping("/collection/listen/list")
    @Operation(summary = "获得我的收藏")
    public CommonResult<PageResult<AppBooksRespVO>> getCollectPage(@Valid BooksPageReqVO pageReqVO) {
        List<CollectDO> collects=collectService.getCollectByUserId(userService.getCurrentUserId());
        List<AppBooksRespVO> audios=new ArrayList<>();
        for(CollectDO collectDO:collects){
            audios.add(booksService.getByBookId(collectDO.getBookId(),null));
        }
        // 分页参数处理
        Long total = (long) audios.size();
        int pageNum = pageReqVO.getPageNo();
        int pageSize = pageReqVO.getPageSize();

        // 计算分页区间
        int start = (pageNum - 1) * pageSize;
        Long end = Math.min(start + pageSize, total);

        // 截取当前页数据
        List<AppBooksRespVO> pagedList = audios.subList(start, Math.toIntExact(end));

        // 构造分页结果
        PageResult<AppBooksRespVO> pageAudios = new PageResult<>();
        pageAudios.setList(pagedList);
        pageAudios.setTotal(total);

        // 返回结果
        return success(BeanUtils.toBean(pageAudios, AppBooksRespVO.class));
    }


    @GetMapping("/listen/list")
    @Operation(summary = "获得绘本的磨耳朵音频")
    public CommonResult<AppBooksRespVO> getBookAudio(@Valid @RequestParam("bookId") Integer bookId,@Valid @RequestParam("sort") String sort) {
        return CommonResult.success(booksService.getByBookId(bookId,sort));
    }


    // 获取当前登录用户 ID（假设已集成鉴权）
//    private Long getCurrentUserId(HttpServletRequest request) {
//        String token = request.getHeader("Authorization");
//        if (token != null && token.startsWith("Bearer ")) {
//            token = token.substring(7);
//        }
//        if (token == null || token.isEmpty()) {
//            throw exception(TOKEN_NOT_EXISTS);
//        }
//
//        try {
//            return Jwts.parser()
//                    .setSigningKey("user".getBytes())
//                    .parseClaimsJws(token)
//                    .getBody()
//                    .get("userId", Long.class);
//        } catch (JwtException e) {
//            throw new RuntimeException("Token 无效或已过期");
//        }
//    }

}
